"""Setup the mtp application"""
import logging

from paste.deploy import appconfig
from pylons import config

from mtp.config.environment import load_environment

log = logging.getLogger(__name__)


initial_pages = {
'Index': """
= Welcome to MTP 
"More Than Picky" (MTP) is a wiki, a very magical wiki at that!

== Features

* wiki creole syntax
* advanced plugin system

=== Plugins

* History: supports viewing history of pages and showing diffs
* Comments: supports per page comments
* Attachments: supports per page attachments and also supplies macros for easily inserting image attachments and attachment links into a page
* RSS: supports per page RSS feeds 


== Links

* Formatting information: [[http://www.wikicreole.org/]]
* List of all macros: [[MacroList]]
* List of all pages: [[PageList]]

Enjoy!
""",
    
'MacroList': """
Available macros:
<<list-macros>>
""",

'PageList': """
All Pages:
<<list-pages>>
""",
}


def create_required_data(model):
    #model.Workspace(
    #    title='',
    #    description='Main Workspace',
    #).save()

    sysuser = model.User(username='system')
    sysuser.save()

    for title, body in initial_pages.iteritems():
        page = model.Page.add(title, sysuser, body, "Initial page")

    perms = (
        (None, 'page', 'view'),
        (None, 'page', 'edit'),
        (None, 'page', 'create'),
    )

    for user, thing, action in perms:
        model.UserPermission.grant(user, thing, action)


def create_test_data(model):
    model.User(
        username='dunk',
        password='dunk',
        realname='dunk',
        email='dunkfordyce@gmail.com',
    ).save()


def setup_config(command, filename, section, vars):
    """Place any commands to setup mtp here"""
    conf = appconfig('config:' + filename)
    load_environment(conf.global_conf, conf.local_conf)

    from mtp import model

    log.info("Setting up database connection...")
    engine = config['pylons.g'].sa_engine

    log.info("Dropping old tables...")
    model.meta.drop_all(bind=engine)
    log.info("Dropping old plugin tables...")
    model.plugin_meta.drop_all(bind=engine)

    log.info("Creating tables...")
    for tablename, table in model.meta.tables.iteritems():
        log.info('Creating table %s...' % tablename)
        table.create(bind=engine, checkfirst=True)

    model.meta.create_all(bind=engine)

    log.info("Creating required data...")
    create_required_data(model)

    if config.get('mtp.create_test_data', 'true') == 'true':
        log.info("Creating test data...")
        create_test_data(model)

    log.info("All done.")


